import React,{useState} from "react"
import Board from "./board";

import { judgeWin } from '../common/common'



function Game(props){
    const initHistory = [{
        'squares': new Array(props.ySize).fill('').map(_ => new Array(props.xSize).fill('')),
        'winner': null,
        'xIsNext': null

    }]
    const [history, setHistory] = useState(initHistory) 
    let handleClick = function(x, y) {
        const current = history[history.length - 1];
        const squares = current.squares.map(ary => {
            return [...ary];
        });
        if (current.winner || squares[y][x]) {
            return;
        }
        squares[y][x] = current.xIsNext ? 'X' : 'O';
        let winner = judgeWin(squares, x, y) ? squares[y][x] : null
        
        setHistory([...history, { xIsNext: !current.xIsNext, winner, squares }])
    }
    let jumpTo = function(move) {
        const newHistory = history.slice(0, move + 1)
        setHistory(newHistory)
    }
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    const winner = current.winner;

    let moves = history.map((step, move) => {
        const desc = move ?`回到第${move}步`: '回到开始';
        return (
            <li>
                <button onClick={() => jumpTo(move)}>{desc}</button>
            </li>
        );
    });
    moves = moves.slice(0, moves.length - 1)
    let status;
    if (winner) {
        status = 'Winner: ' + winner;
    } else {
        status = 'Next player: ' + (current.xIsNext ? 'X' : 'O');
    }


    return (
        <div className="game">
            <div className="game-board">
                <Board xSize={props.xSize} ySize={props.ySize} squares={squares} 
                onclick={(x, y) => handleClick(x, y)} />
            </div>
            <div className="game-info">
                <div>{status}</div>
                <ol>{moves}</ol>
            </div>
        </div>
    );
}
export default Game